import { Controller, Get, Post, Body, Patch, Param, Delete, Inject, Res, UseGuards, ValidationPipe, Req, UseInterceptors, ClassSerializerInterceptor } from '@nestjs/common';
import { UserService } from './user.service';
import { CreateUserDto } from './dto/create-user.dto';
import { UpdateUserDto } from './dto/update-user.dto';
import { JwtService } from '@nestjs/jwt';
import { Request, Response } from 'express';
import { LoginGuard } from 'src/login.guard';
import { AuthGuard } from '@nestjs/passport';
import { Role } from './entities/role.entity';
import { ApiBody, ApiTags } from '@nestjs/swagger';


@ApiTags('user')
@Controller('user')
export class UserController {
    constructor(private readonly userService: UserService) { }
    @Inject()
    jwtService: JwtService;

    @ApiBody({
        type: CreateUserDto
    })
    @Post('login')
    login(@Body(ValidationPipe) user: CreateUserDto) {
        return this.userService.login(user)
    }

    // passport策略 
    @UseGuards(AuthGuard('local'))
    @Post('new_login')
    async newLogin(@Req() req: Request) {
        // 通过后 会自动把user 挂载到 request上
        const { id, roles } = req.user
        const token = this.jwtService.sign({
            userId: id,
            roles: roles.map((role) => role.id) // 存入时 只需要role的id
        }, { expiresIn: '1d' })

        await this.userService.updateToken(id, token)
        req.user.token = token
        return req.user
    }

    @Post('register')
    register(@Body(ValidationPipe) user: CreateUserDto) {
        return this.userService.register(user)
    }

    @Get('all')
    @UseGuards(LoginGuard)
    @UseInterceptors(ClassSerializerInterceptor)
    getUserInfo() {
        return this.userService.findAll()
    }
}
